package com.demo.web.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.demo.controller.BaseController;
import com.demo.exception.ServiceException;
import com.demo.model.Excel.Excel;
import com.demo.model.Jobassembly.Jobassembly;
import com.demo.model.Jobassembly.JobassemblyQuery.JobassemblyQuery;
import com.demo.model.SysUser.SysUser;
import com.demo.service.Jobassembly.JobassemblyService;
import com.demo.service.User.SysUserservice;
import com.demo.tool.ReturnResult;
import com.demo.tool.Token;
import com.sun.deploy.net.URLEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.rmi.ServerException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/api/backstage/jobassembly")
public class Jobassemblycontroller extends BaseController<Jobassembly, JobassemblyQuery, Integer> {

    @Autowired
    private JobassemblyService jobassemblyService;

    @Autowired
    private SysUserservice sysUserservice;

    @Autowired
    private Token tokenTool;

    //获取生产计划排期接口
    @GetMapping("/schedulingList")
    public ReturnResult schedulingList() {
        return ReturnResult.success(jobassemblyService.schedulingList());
    }

    @PostMapping("/pictureUpload")
    @ResponseBody
    public ReturnResult pictureUpload(List<MultipartFile> headImages, HttpServletRequest request) {
        //上传文件路径集合
        List<String> list = new ArrayList<>();
        // 创建一个StringBuilder对象
        StringBuilder sb = new StringBuilder();
        //实际路径
        String filePath = "";
        //相对路径
        String relativePath = "";

        if (headImages.size() <= 0) {
            throw new ServiceException("您还没有上传图像");
        } else if (headImages.size() > 10) {
            throw new ServiceException("最多可上传十个文件");
        }

        for (int i = 0; i < headImages.size(); i++) {
            MultipartFile multipartFile = headImages.get(i);
            //获取上传 文件的后缀
            //获取文件原名
            String filename = multipartFile.getOriginalFilename();
            System.out.println("原名字" + filename);
            String suffix = filename.substring(filename.lastIndexOf(".") + 1);
            System.out.println("截取" + suffix);
            //文件合法判断变量
            Boolean typeisture = false;
            if (suffix.equals("pdf") || suffix.equals("zip") || suffix.equals("rar") || suffix.equals("png") || suffix.equals("jpg") || suffix.equals("jpeg")) {
                typeisture = true;
            } else {
                throw new ServiceException("文件类型错误");
            }

            if (typeisture) {
                //生成随机的存储文件的名字
                filename = UUID.randomUUID() + "." + suffix;
                //相对路径
                relativePath = "http://localhost:8009/img/" + filename;
                //实际路径
                filePath = System.getProperty("user.dir") + "\\web\\src\\main\\resources\\static\\img";
                System.out.println(filename);
                System.out.println(filePath);
                //如果不存在文件夹 就创建
                if (!new File(filePath).exists()) {
                    new File(filePath).mkdirs();
                }
                File dest = new File(filePath + File.separator + filename);
                try {
                    multipartFile.transferTo(dest);
                    list.add(relativePath);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            for (int l = 0; l < list.size(); l++) {
                if (list.get(l) == list.get(list.size() - 1)) {
                    sb.append(list.get(l));
                } else {
                    sb.append(list.get(l)).append(",");
                }
            }


            System.out.println("当前文件路径集合" + sb);
            //获取当前用户
            String token = request.getHeader("Authorization");
            Long uid = null;
            SysUser sysUser = null;
            if (!StringUtils.hasLength(token) || token.isEmpty()) {
                ReturnResult.error("token为空");
            } else {
                uid = tokenTool.GetUserUidByToken(token);
                System.out.println("当前uid为" + uid);
                sysUser = sysUserservice.getUserOneByUid(uid);
                sysUser.setHeadSculpture(sb.toString());
            }
        }

        return ReturnResult.success(JSONArray.toJSON(list));
    }


    //导出excel文件 该方法接收一个HttpServletResponse对象作为参数，并设置响应头信息，以便浏览器下载Excel文件。
    @GetMapping("/downloadExcel")
    public void downloadExcel(HttpServletResponse httpServletResponse) throws IOException {
        try {
            List<Jobassembly> list = new ArrayList<>();
            List<Excel> excels = new ArrayList<>();
            list = jobassemblyService.findAll(null);
            excels = list.stream().map(i -> {
                Excel excel = new Excel();
                BeanUtils.copyProperties(i, excel);
                return excel;
            }).collect(Collectors.toList());
            //去除不需要的列
//            Set<String> excludeColumnFiledNames=new HashSet<>();
//            excludeColumnFiledNames.add("remark");
//            excludeColumnFiledNames.add("production_job_material");
//            excludeColumnFiledNames.add("status");


            httpServletResponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); //设置响应内容类型
            httpServletResponse.setCharacterEncoding("utf-8");//编码
            // 设置文件名, ps:把字符串中所有的'+'替换成'%20'，在URL中%20代表空格
            String fileName = URLEncoder.encode("作业装配表", "UTF-8").replaceAll("\\+", "%20");
            httpServletResponse.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");//设置响应头
            EasyExcel.write(httpServletResponse.getOutputStream(), Excel.class).sheet("作业装配数据").doWrite(excels);
        } catch (Exception e) {
            throw new ServerException(e.getMessage());
        }


    }


    //导入excel文件
    @PostMapping("/importExcel")
    public ReturnResult importExcel(MultipartFile file) throws IOException, ParseException {
        List<Excel> newlist = new ArrayList<>();
        List<Jobassembly> jobassemblyList = new ArrayList<>();
        if (file != null) {
            List<Excel> list = EasyExcel.read(file.getInputStream()).head(Excel.class).sheet().doReadSync();
            //将新的excel数据添加进集合
            list.forEach(data -> {
                if (data.getSerialNumber() == null) {
                    newlist.add(data);
                }
            });

            //转化为实际加入的集合
            jobassemblyList = newlist.stream().map(i -> {
                Jobassembly jobassembly = new Jobassembly();
                BeanUtils.copyProperties(i, jobassembly);
                return jobassembly;
            }).collect(Collectors.toList());


            System.out.println(jobassemblyList.size() + "这是size");
            jobassemblyService.saveAll(jobassemblyList);
        }
        return ReturnResult.success(jobassemblyService.findAllpaging(null, null, null));
    }

}
